import java.util.Date;
import java.util.Calendar;
import java.text.SimpleDateFormat;

public class Cache {
	private String filename;
	private String contents;
	//Time Cache was last validated
	private Date tcDate = null;
	//Time file was last modified at server
	private Date tmDate = null;
	private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); 
	private boolean empty = true;
	
	public Cache() {
	
	}
	
	public Cache(String filename,String t_mserver,String contents) {
		this.filename = filename;
		this.contents = contents;
		this.tcDate = parseDate(t_mserver);
		this.tmDate = parseDate(t_mserver);
		empty = false;
	}
	
   /**
	* Checks whether the cache contain contents of a certain file
	*/
	public boolean exists(String fname) {
		if(empty) {
			return false;
		} else {
			return (filename.toLowerCase() == fname.toLowerCase());
		}
	}
	
   /**
	* Checks whether the cache needs to be evaluated
	* @return true	if T - Tc < t, otherwise false
	*/
	public boolean evaluateCache(int t) {
		Date nowDate = parseDate(now());
		if(!((getTimeDifference(nowDate,tcDate)) < t)) {
			return true;
		} 
		return false;
	}
	
   /**
	* Checks whether the cache is valid by comparing 
	* values of Tm and Tm_server
	* Ereturn true	if
	*/
	public boolean isCacheValid(String t_mserver) {
		//No cache
		if(tmDate == null) {
			return false;
		}
		Date tmserverDate = parseDate(t_mserver);
		if(tmDate.compareTo(tmserverDate) == 0) {
			//Update Tc value
			tcDate = parseDate(now());
			return true;
		}
		return false;
	}
	
   /**
	* Get a whole content of the cache
	*/
	public String getContents() {
		return contents;
	}
	
   /**
	* Get a partial content of the cache
	*/
	public String getContents(int offset,int numOfBytes) {
		String result = "";
		try {
			result = "File contents: " + new String(contents.getBytes(),offset,numOfBytes);
		} catch(IndexOutOfBoundsException e) {
			result = "Out of bounds exception";
		}
		return result;
	}
	
   /**
	* Get current time in the format "hh:mm:ss"
	*/
	private String now() {
		Calendar cal = Calendar.getInstance();
		return sdf.format(cal.getTime());
	}
	
   /**
	* Get difference of two times in seconds
	*/
	private long getTimeDifference(Date date1,Date date2) {
		long result = Math.abs((date1.getTime() - date2.getTime())/1000);
		return result;
	}
	
	private Date parseDate(String str) {
		try {
			return sdf.parse(str);
		} catch(java.text.ParseException e) {
			return null;
		}
	}
}